<template>
  <main-content title="商城配置">
    <template #fixed-bottom>
      <div class="fixed-button">
        <el-button
          v-has="['08050101']"
          type="primary"
          :loading="loading"
          @click="_saveConfigure(settingFormRef)"
        >
          保存
        </el-button>
      </div>
    </template>

    <el-form
      ref="settingFormRef"
      :model="settingForm"
      :rules="settingFormRules"
      label-width="120px"
    >
      <div class="form-title">
        基础配置
      </div>

      <el-form-item
        prop="mallName"
        label="商城名称"
      >
        <el-input
          v-model="settingForm.mallName"
          placeholder="请输入商城名称"
          maxlength="15"
          show-word-limit
        />
      </el-form-item>

      <el-form-item
        prop="mallName"
        label="规则"
      >
        <el-button
          type="primary"
          @click="dialogMessage.showDiscountRule = true"
        >
          折扣规则
        </el-button>
        <el-button
          type="primary"
          @click="dialogMessage.showPurchaseRule = true"
        >
          限购规则
        </el-button>
      </el-form-item>

      <el-form-item
        label="商城导航"
        prop="enableTab"
      >
        <el-switch
          v-model="mallPageSettings.enableTab"
          @change="handleEnableTab"
        />
      </el-form-item>

      <template v-if="mallPageSettings.enableTab">
        <el-form-item
          label="导航背景"
          prop="tabBackground"
        >
          <el-color-picker v-model="mallPageSettings.background" />
        </el-form-item>

        <el-form-item
          label="导航样式"
          prop="tabStyle"
        >
          <el-radio-group v-model="mallPageSettings.tabStyle">
            <el-radio-button label="IconAndText">
              图标和文字
            </el-radio-button>
            <el-radio-button label="Icon">
              仅图片
            </el-radio-button>
            <el-radio-button label="Text">
              仅文字
            </el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="mallPageSettings.tabStyle == 'IconAndText' || mallPageSettings.tabStyle == 'Text'"
          label="文字颜色"
          prop="tabFontColor"
        >
          默认:
          <el-color-picker v-model="mallPageSettings.colorOff" />&nbsp; 
          激活:
          <el-color-picker v-model="mallPageSettings.colorOn" />
        </el-form-item>

        <el-form-item
          label="导航内容"
          prop="tabNavContent"
        >
          <div class="nav-content">
            <div class="tab-icons">
              <div
                v-for="(item, index) in mallPageSettings.tabs"
                :key="index"
                class="img-wrapper"
                :class="{'img-wrapper__selected': currentTab === index}"
                @click="currentTab = index"
              >
                <el-image
                  v-if="getTabIcon(mallPageSettings.tabs[index], 'off')"
                  :src="getTabIcon(mallPageSettings.tabs[index], 'off')"
                  :alt="item.name"
                />
                <div v-else>
                  请上传图标
                </div>

                <div
                  class="close"
                  @click.stop="removeTab(index)"
                >
                  <el-icon><Close /></el-icon>
                </div>
              </div>

              <div
                v-if="mallPageSettings.tabs.length < maxAddableTabs"
                class="add"
                @click="addTab"
              >
                <el-icon><Plus /></el-icon>
              </div>
            </div>
            <div class="tabs">
              <el-form-item
                label="设置首页"
                class="tab-row"
                prop="tabHomePage"
              >
                <el-switch
                  v-model="mallPageSettings.tabs[currentTab].homePage"
                  :before-change="setHomePageBeforeChange"
                />
              </el-form-item>

              <el-form-item
                v-if="mallPageSettings.tabStyle === 'IconAndText' || mallPageSettings.tabStyle === 'Text'"
                label="导航名称"
                class="tab-row"
                prop="tabName"
              >
                <el-input
                  v-model="mallPageSettings.tabs[currentTab].name"
                  placeholder="名称"
                />
              </el-form-item>
            
              <el-form-item
                label="图标"
                class="tab-row"
                prop="tabIcon"
              >
                <div class="uploader">
                  <ImageUploadV2
                    :model-value="getTabIcon(mallPageSettings.tabs[currentTab], 'off')"
                    @change="handleIconUploadChange($event, mallPageSettings.tabs[currentTab], 'off')"
                  >
                    <template #hover-layer="{replace, index}">
                      <el-button
                        link
                        @click="replace(index)"
                      >
                        替换
                      </el-button>
                    </template>
                  </ImageUploadV2>
                  <div class="uploader-placeholder">
                    默认
                  </div>
                </div>

                <div class="uploader">
                  <ImageUploadV2
                    :model-value="getTabIcon(mallPageSettings.tabs[currentTab], 'on')"
                    @change="(value) => handleIconUploadChange(value, mallPageSettings.tabs[currentTab], 'on')"
                  >
                    <template #hover-layer="{replace, index}">
                      <el-button
                        link
                        @click="replace(index)"
                      >
                        替换
                      </el-button>
                    </template>
                  </ImageUploadV2>
                  <div class="uploader-placeholder">
                    激活
                  </div>
                </div>
              </el-form-item>

              <el-form-item
                label="跳转链接"
                class="tab-row"
                prop="tabPageId"
              >
                <div
                  v-if="mallPageSettings.tabs[currentTab].homePage"
                  class="href-wrapper  href-wrapper__homepage"
                >
                  {{ mallPageSettings.tabs[currentTab].pageName }}（不可更改）
                </div>
                <div
                  v-else-if="mallPageSettings.tabs[currentTab].pageId"
                  class="href-wrapper"
                  @click="addHref(currentTab)"
                >
                  <el-icon><Link /></el-icon>
                  {{ mallPageSettings.tabs[currentTab].pageName }}
                </div>
                <div
                  v-else
                  class="href-wrapper"
                  @click="addHref(currentTab)"
                >
                  <el-icon><Link /></el-icon>
                  <span>请选择链接</span>
                </div>
              </el-form-item>
            </div>
          </div>
        </el-form-item>

        <!-- <el-form-item label="主页链接">
          {{ previewPath }}#/mall/{{ settingForm.mallCode }}
        </el-form-item> -->
      </template>


      <div class="form-title">
        订单配置
      </div>
      <el-form-item
        prop="payConfigId"
        label="支付配置"
      >
        <!-- <el-select v-model="settingForm.payConfigId" placeholder="请选择支付配置" @change="setPayType">
          <el-option
              v-for="item in payConfigList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select> -->
        <ScSelector
          v-model="settingForm.payConfigId"
          placeholder="请选择支付配置"
          type="config"
          :params="{ attach: 'pay' }"
          @change-selected="setPayType"
        >
          <template #expand-pop="{ data }">
            <div
              v-if="data"
              class="detail-container"
            >
              <div class="detail-text">
                <h3>
                  {{ data.info.name }}
                </h3>
              </div>
              <div class="detail-text_line">
                配置类型：{{ data.info.externalTypeName }}
              </div>
              <div class="detail-text_line">
                所属平台：{{ data.info.externalPlatformTypeName }}
              </div>
              <div class="detail-text_line">
                配置标识：{{ data.info.unique }}
              </div>
              <div class="detail-text_line">
                描述：{{ data.info.remark || "暂无" }}
              </div>
            </div>
          </template>
        </ScSelector>
      </el-form-item>
      <el-form-item
        label="正常订单超过"
        prop="orderTimeout"
      >
        <el-input
          v-model.number="settingForm.orderTimeout"
          type="number"
        >
          <template #append>
            分
          </template>
        </el-input>
        <span class="description"> 未付款，订单自动关闭 </span>
      </el-form-item>
      <el-form-item
        label="发货超过"
        prop="deliverTimeout"
      >
        <el-input
          v-model.number="settingForm.deliverTimeout"
          type="number"
        >
          <template #append>
            天
          </template>
        </el-input>
        <span class="description"> 未收货，订单自动完成 </span>
      </el-form-item>
      <el-form-item
        label="订单完成超过"
        prop="serviceTimeout"
      >
        <el-input
          v-model.number="settingForm.serviceTimeout"
          type="number"
        >
          <template #append>
            天
          </template>
        </el-input>
        <span class="description"> 自动结束交易，不能申请售后 </span>
      </el-form-item>
      <!--      <div class="form-title">会员折扣</div>-->
      <!--      <el-form-item label="会员折扣：" prop="discount">-->
      <!--        <el-input v-model="settingForm.discount" @blur="handleDiscountBlur">-->
      <!--          <template #append>-->
      <!--            折-->
      <!--          </template>-->
      <!--        </el-input>-->
      <!--        <span class="description">-->
      <!--          （例：1折，2.5折，7折，7.5折）-->
      <!--        </span>-->
      <!--      </el-form-item>-->


      <div class="form-title">
        登录配置
      </div>

      <el-form-item
        prop="loginType"
        label="登录方式"
      >
        <el-radio-group v-model="settingForm.loginType">
          <el-radio label="sms">
            手机号码登录
          </el-radio>
          <el-radio label="external">
            外部授权登录
          </el-radio>
        </el-radio-group>

        <el-form-item
          v-if="settingForm.loginType == 'external'"
          label-width="20px"
          prop="externalLoginConfigId"
        >
          <ScSelector
            v-model="settingForm.externalLoginConfigId"
            placeholder="请选择登录页"
            type="config"
            :params="{ attach: 'userLogin' }"
          >
            <template #expand-pop="{ data }">
              <div
                v-if="data"
                class="detail-container"
              >
                <div class="detail-text">
                  <h3>
                    {{ data.info.name }}
                  </h3>
                </div>
                <div class="detail-text_line">
                  配置类型：{{ data.info.externalTypeName }}
                </div>
                <div class="detail-text_line">
                  所属平台：{{ data.info.externalPlatformTypeName }}
                </div>
                <div class="detail-text_line">
                  配置标识：{{ data.info.unique }}
                </div>
                <div class="detail-text_line">
                  描述：{{ data.info.remark || "暂无" }}
                </div>
              </div>
            </template>
          </ScSelector>
        </el-form-item>
      </el-form-item>

      <template v-if="settingForm.loginType == 'sms'">
        <el-form-item
          label="登录页面"
          prop="loginStyleId"
        >
          <el-radio-group v-model="loginStyleIdModel">
            <el-radio :label="-1">
              系统默认
            </el-radio>
            <el-radio :label="-2">
              自定义
            </el-radio>
          </el-radio-group>
          <el-form-item
            v-if="loginStyleIdModel !== -1"
            label-width="20px"
            prop="loginStyleId"
          >
            <ScSelector
              v-model="settingForm.loginStyleId"
              placeholder="请选择登录页"
              type="loginStyle"
              :params="{}"
            >
              <template #expand-pop="{ data }">
                <div
                  v-if="data"
                  class="detail-container"
                >
                  <div class="detail-text">
                    <h3>
                      {{ data.info.title }}
                    </h3>
                  </div>
                  <el-image
                    style="width: 180px; height: 230px"
                    :src="data.info.cover"
                    fit="fill"
                  />
                </div>
              </template>
            </ScSelector>
          </el-form-item>
        </el-form-item>
      </template>

      <template v-if="settingForm.loginType == 'sms'">
        <el-form-item
          prop="externalSmsConfigId"
          label="短信配置"
        >
          <el-radio-group v-model="externalSmsConfigIdModel">
            <el-radio :label="-1">
              系统默认
            </el-radio>
            <el-radio :label="-2">
              自定义
            </el-radio>
          </el-radio-group>
          <el-form-item
            v-if="externalSmsConfigIdModel !== -1"
            label-width="20px"
            prop="externalSmsConfigId"
          >
            <ScSelector
              v-model="settingForm.externalSmsConfigId"
              placeholder="请选择验证码"
              type="config"
              :params="{ attach: 'sms_code' }"
            >
              <template #expand-pop="{ data }">
                <div
                  v-if="data"
                  class="detail-container"
                >
                  <div class="detail-text">
                    <h3>
                      {{ data.info.name }}
                    </h3>
                  </div>
                  <div class="detail-text_line">
                    配置类型：{{ data.info.externalTypeName }}
                  </div>
                  <div class="detail-text_line">
                    所属平台：{{ data.info.externalPlatformTypeName }}
                  </div>
                  <div class="detail-text_line">
                    配置标识：{{ data.info.unique }}
                  </div>
                  <div class="detail-text_line">
                    描述：{{ data.info.remark || "暂无" }}
                  </div>
                </div>
              </template>
            </ScSelector>
          </el-form-item>
        </el-form-item>
      </template>
    </el-form>
    <!-- 通知配置start -->
    <div class="form-title">
      通知配置
    </div>
    <NoticeConfig
      ref="noticeConfigRef"
      service-type="mall"
      :mall-id="mallConfig.id"
    />
    <!-- 通知配置end-->

    <DiscountRule
      :id="mallConfig.id"
      :show-dialog="dialogMessage.showDiscountRule"
      belong="mall"
      @confirm="confirm"
      @cancel="cancel"
    />
    <PurchaseRestrictionRule
      :id="mallConfig.id"
      :show-dialog="dialogMessage.showPurchaseRule"
      belong="mall"
      @confirm="confirm"
      @cancel="cancel"
    />

    <MallPageSelector
      v-model="selectorVisible"
      @confirm="onMallPageSelect"
      @close="onClose"
    />
  </main-content>
</template>
<script lang="ts">
export default {
  name: "MallSystemMallConfig",
};
</script>
<script setup lang="ts">
import { Ref, UnwrapRef, ComputedRef } from "vue";
import { FormInstance, FormRules } from "element-plus";
import { InternalRuleItem } from "async-validator";
import { Plus } from "@element-plus/icons-vue"
import { getOrderConfigure, saveConfigure } from "@/api/pointsMall";
import {
  IOrderConfigData,
  MallConfig,
} from "@/api/modules/pointsMall";
import sysConfigApi from "@/api/sysConfigApi";
import { getHomePage } from "@/api/pointsMall";
import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig";
import DiscountRule from "@/views/pointsMall/rules/discountRule.vue";
import PurchaseRestrictionRule from "@/views/pointsMall/rules/purchaseRestrictionRule.vue";
import MallPageSelector from "@/components/mallPageSelector/MallPageSelector.vue";
import NoticeConfig from "@/components/noticeConfig/index.vue"
import HomeActive from "@/assets/images/mallsetting/home-active.png"
import Home from "@/assets/images/mallsetting/home.png"
import FenleiActive from "@/assets/images/mallsetting/fenlei-active.png"
import Fenlei from "@/assets/images/mallsetting/fenlei.png"
import WodeActive from "@/assets/images/mallsetting/wode-active.png"
import Wode from "@/assets/images/mallsetting/wode.png"


const store = useStore();

const previewPath = `${(window as any).VUE_APP_URL[import.meta.env.MODE].appPreviewPath
}${store.state.user.merchant.merchantCode}`;

const { mallConfig } = useMallConfig();
const dialogMessage = ref({
  showDiscountRule: false,
  showPurchaseRule: false,
});
const noticeConfigRef = ref()
const settingFormRef: Ref<FormInstance | undefined> = ref();
const settingForm: UnwrapRef<MallConfig> = reactive({
  orderTimeout: null,
  deliverTimeout: null,
  serviceTimeout: null,
  mallName: null,
  payConfigId: null,
  payType: null,
  discount: "10",
  mallPageSettings: "",
  mallCode: "",
  loginType: "sms",
  loginStyleId: -1,
  externalSmsConfigId: -1,
  externalLoginConfigId: null,
  loginStyleIdSel: null,
  externalSmsConfigIdSel: null,
});

const iconModel = ref([])

const DEFAULT_TABS = [
  {
    name: "首页",
    pageId: null,
    pageName: "",
    iconOn: "",
    iconOff: [],
    useDefaultIconOn: true,
    useDefaultIconOff: true,
    defaultIconKey: 'HOME',
  },
  {
    name: "分类",
    pageId: null,
    pageName: "",
    iconOn: "",
    iconOff: "",
    useDefaultIconOn: true,
    useDefaultIconOff: true,
    defaultIconKey: "FENLEI"
  },
  {
    name: "我的",
    pageId: null,
    pageName: "",
    iconOn: "",
    iconOff: "",
    useDefaultIconOn: true,
    useDefaultIconOff: true,
    defaultIconKey: "WODE"
  },
]

//商城主页设置
const mallPageSettings = reactive({
  enableTab: false,
  tabStyle: "IconAndText", //Icon/Text
  background: "#fff",
  colorOn: "#ff0000",
  colorOff: "#000000",
  pageId: null,
  pageName: null,
  tabs: JSON.parse(JSON.stringify(DEFAULT_TABS)),
});

const handleEnableTab = (value: boolean) => {
  if (value) {
    mallPageSettings.tabs = JSON.parse(JSON.stringify(DEFAULT_TABS))
  } else {
    currentTab.value = 0;
    mallPageSettings.tabs = []
  }
}

const maxAddableTabs = ref(5); // 最大tab数量
const addTab = () => {
  if (mallPageSettings.tabs.length < maxAddableTabs.value) {
    mallPageSettings.tabs.push({
      name: "",
      pageId: null,
      pageName: "",
      iconOn: "",
      iconOff: "",
    });
    currentTab.value = mallPageSettings.tabs.length - 1
  }
};
const removeTab = (ind: number) => {
  if (mallPageSettings.tabs.length <= 1) {
    ElMessage.warning("启用商城导航至少需保留一个TAB")
    return
  }
  currentTab.value = currentTab.value - 1 >= 0 ? currentTab.value - 1 : 0;
  mallPageSettings.tabs.splice(ind, 1);
};

const currentTab = ref(0);

const getTabIcon = (tabConfig, type) => {
  if (type === 'on') {
    if (tabConfig.useDefaultIconOn) {
      switch (tabConfig.defaultIconKey) {
        case "HOME": 
          return HomeActive;
        case "FENLEI":
          return FenleiActive;
        case "WODE":
          return WodeActive;
        default:
          return HomeActive
      }
    } else {
      return tabConfig.iconOn
    }
  } else {
    if (tabConfig.useDefaultIconOff) {
      switch (tabConfig.defaultIconKey) {
        case "HOME": 
          return Home;
        case "FENLEI":
          return Fenlei;
        case "WODE":
          return Wode;
        default:
          return Home
      }
    } else {
      return tabConfig.iconOff
    }
  }
}

const setHomePageBeforeChange = async () => {
  const rs = await getHomePage({ id: mallConfig.value.id })
  if (rs.code === 200) {
    if (rs.payload) {
      mallPageSettings.tabs[currentTab.value].pageId = rs.payload.id
      mallPageSettings.tabs[currentTab.value].pageName = rs.payload.name

      mallPageSettings.tabs.forEach((item, index) => {
        if (currentTab.value !== index) {
          item.homePage = false
        }
      })
      return true
    } else {
      ElMessage.warning("未指定页面，请前往商城装修->页面管理，指定页面为首页")
      return false
    }
  } else {
    return false
  }
}

const selectorVisible = ref(false);
const addHref = (ind: number) => {
  currentTab.value = ind;
  selectorVisible.value = true;
};
const onMallPageSelect = (link: any) => {
  selectorVisible.value = false;
  mallPageSettings.tabs[currentTab.value].pageId = link.id;
  mallPageSettings.tabs[currentTab.value].pageName = link.name;
};
const onClose = () => {
  selectorVisible.value = false;
};
const onUploadSuccess = (file: any, item: any, type: any) => {
  if (type == "on") {
    item.iconOn = file.url;
    item.useDefaultIconOn = false;
  } else if (type == "off") {
    item.iconOff = file.url;
    item.useDefaultIconOff = false;
  }
};

const handleIconUploadChange = (files: {name: string; url: string}[], tabConfig: any, type: string) => {
  if (type === "on") {
    tabConfig.iconOn = files?.[0]?.url ?? '';
    tabConfig.useDefaultIconOn = false;
  } else if (type == "off") {
    tabConfig.iconOff = files?.[0]?.url ?? '';
    tabConfig.useDefaultIconOff = false;
  }
}

const payConfigList = ref([] as any);
const validateInteger = (rule: any, value: any, callback: any) => {
  if (!/(^[0-9]\d*$)/.test(value)) {
    return callback(new Error("需为整数"));
  } else {
    callback();
  }
};
const settingFormRules: Ref<FormRules> = ref({
  enableTab: [ {
    required: true,
    validator(rule: InternalRuleItem, value: undefined, callback: (e?: Error | string) => void) {
      if (mallPageSettings.enableTab === null || mallPageSettings.enableTab === undefined) {
        callback("请配置是否启用商城导航")
        return
      }

      callback()
    },
  } ],
  tabBackground: [ {
    required: true,
    validator(rule: InternalRuleItem, value: undefined, callback: (e?: Error | string) => void) {
      if (mallPageSettings.background === null || mallPageSettings.background === undefined) {
        callback("请配置导航背景")
        return
      }

      callback()
    },
  } ],
  tabStyle: [ {
    required: true,
    validator(rule: InternalRuleItem, value: undefined, callback: (e?: Error | string) => void) {
      if (mallPageSettings.tabStyle === null || mallPageSettings.tabStyle === undefined) {
        callback("请配置导航样式")
        return
      }

      callback()
    },
  } ],
  tabFontColor: [ {
    required: true,
    validator(rule: InternalRuleItem, value: undefined, callback: (e?: Error | string) => void) {
      if (mallPageSettings.colorOff === null || mallPageSettings.colorOff === undefined) {
        callback("请配置默认的文字颜色")
        return
      }

      if (mallPageSettings.colorOn === null || mallPageSettings.colorOn === undefined) {
        callback("请配置激活的文字颜色")
        return
      }

      callback()
    },
  } ],
  tabNavContent: [ {
    required: true,
    validator(rule: InternalRuleItem, value: undefined, callback: (e?: Error | string) => void) {
      if (!mallPageSettings.tabs.find(item => item.homePage)) {
        callback("请至少指定一个导航TAB为首页")
        return
      }

      callback()
    },
  } ],
  tabHomePage: [ {
    required: true,
    validator(rule: InternalRuleItem, value: undefined, callback: (e?: Error | string) => void) {
      callback();
    }
  } ],
  tabName: [ {
    required: true,
    validator(rule: InternalRuleItem, value: undefined, callback: (e?: Error | string) => void) {
      for (let i = 0; i < mallPageSettings.tabs.length; i++) {
        if ((mallPageSettings.tabStyle === 'IconAndText' || mallPageSettings.tabStyle === 'Text') && !mallPageSettings.tabs[i].name) {
          callback("请设置导航名称")
          currentTab.value = i;
          return
        }
      }
      callback();
    }
  } ],
  tabIcon: [ {
    required: true,
    validator(rule: InternalRuleItem, value: undefined, callback: (e?: Error | string) => void) {
      for (let i = 0; i < mallPageSettings.tabs.length; i++) {
        if (mallPageSettings.tabStyle === 'IconAndText' || mallPageSettings.tabStyle === 'Icon') {
          if (!mallPageSettings.tabs[i].useDefaultIconOn) {
            if (!mallPageSettings.tabs[i].iconOff) {
              callback("请设置激活图标")
              currentTab.value = i;
              return
            }
          }

          if (!mallPageSettings.tabs[i].useDefaultIconOff) {
            if (!mallPageSettings.tabs[i].iconOff) {
              callback("请设置默认图标")
              currentTab.value = i;
              return
            }
          }
        }
      }
      callback();
    }
  } ],
  tabPageId: [ {
    required: true,
    validator(rule: InternalRule, value: undefined, callback: (e?: Error | string) => void) {
      for (let i = 0; i < mallPageSettings.tabs.length; i++) {
        if (!mallPageSettings.tabs[i].pageId) {
          callback("请设置跳转链接")
          currentTab.value = i;
          return
        }
      }
      callback();
    }
  } ],
  orderTimeout: [
    {
      message: "请输入超时时间（分）",
      required: true,
      trigger: "blur",
    },
    {
      message: "需为大于0的整数",
      trigger: "blur",
      validator: validateInteger,
    },
  ],
  deliverTimeout: [
    {
      message: "请输入超时时间（天）",
      required: true,
      trigger: "blur",
    },
    {
      message: "需为大于0的整数",
      trigger: "blur",
      validator: validateInteger,
    },
  ],
  serviceTimeout: [
    {
      message: "请输入超时时间（天）",
      required: true,
      trigger: "blur",
    },
    {
      message: "需为大于0的整数",
      trigger: "blur",
      validator: validateInteger,
    },
  ],
  payConfigId: [
    {
      message: "请选择支付配置",
      required: false,
      trigger: "blur",
    },
  ],
  mallName: [
    {
      message: "请输入商城名称",
      required: true,
      trigger: "blur",
    },
  ],
  discount: [
    {
      trigger: "blur",
      required: true,
      validator(rule: any, val: string, callback: (msg: string) => void) {
        if (isNaN(Number(val)) || Number(val) < 1 || Number(val) > 10) {
          callback(
            "会员折扣需为大于等于1，小于等于10，步长为0.5的数值，例：1.5，6.5，7，8，9，9.5"
          );
        }
      },
    },
  ],
  loginType: [ { required: true, message: "请选择登录方式", trigger: "change" } ],
  loginStyleId: [ { required: true, message: "请选择配置", trigger: "change" } ],
  externalSmsConfigId: [ { required: true, message: "请选择配置", trigger: "change" } ],
  externalLoginConfigId: [ { required: true, message: "请选择配置", trigger: "change" } ],
});

const _saveConfigure = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return;
  }

  formEl.validate(async (validate, filed) => {
    if (validate) {
      settingForm.mallPageSettings = JSON.stringify(mallPageSettings);
      const millisecondTimeForm: IOrderConfigData = {
        ...settingForm,
        mallId: 0,
      };
      millisecondTimeForm.mallId = mallConfig.value.id;
      millisecondTimeForm.orderTimeout = Number(
        transferToMilliseconds(Number(settingForm["orderTimeout"]), "minute")
      );
      millisecondTimeForm.deliverTimeout = Number(
        transferToMilliseconds(Number(settingForm["deliverTimeout"]), "day")
      );
      millisecondTimeForm.serviceTimeout = Number(
        transferToMilliseconds(Number(settingForm["serviceTimeout"]), "day")
      );
      //添加通知配置参数
      const noticeData = await noticeConfigRef.value.validForm()
      millisecondTimeForm.noticeType = noticeData.noticeType
      millisecondTimeForm.noticePhones = noticeData.noticePhones
      millisecondTimeForm.noticeWebhookUrls = noticeData.noticeWebhookUrls
      millisecondTimeForm.noticeUserIds = noticeData.noticeUserIds ? String(noticeData.noticeUserIds) : undefined

      const rs = await saveConfigure(millisecondTimeForm);

      if (rs.code === 200) {
        ElMessage.success("保存成功");
      }
    } else {
      console.log(filed);
    }
  });
};

const ratio = {
  day: 1000 * 60 * 60 * 24,
  hour: 1000 * 60 * 60,
  minute: 1000 * 60,
};
const formUnit = {
  orderTimeout: "minute",
  deliverTimeout: "day",
  serviceTimeout: "day",
};
const transferToMilliseconds = (
  val: number | string,
  originType: "day" | "hour" | "minute"
) => {
  let _val;
  if (typeof val === "string") {
    if (isNaN(Number(val))) {
      return val;
    } else {
      _val = Number(val);
    }
  } else {
    _val = val;
  }
  return _val * ratio[originType];
};

const transferToRealTime: (
  val: number,
  targetType: "day" | "hour" | "minute"
) => number = (val, targetType) => {
  return val / ratio[targetType];
};

const loading: Ref<boolean> = ref(false);
const _getOrderConfigure = async () => {
  loading.value = true;
  const rs: any = await getOrderConfigure({ id: mallConfig.value.id });

  if (rs.code === 200 && rs.payload) {
    settingForm.orderTimeout = transferToRealTime(
      rs.payload.orderTimeout,
      "minute"
    );
    settingForm.deliverTimeout = transferToRealTime(
      rs.payload.deliverTimeout,
      "day"
    );
    settingForm.serviceTimeout = transferToRealTime(
      rs.payload.deliverTimeout,
      "day"
    );
    settingForm.mallName = rs.payload.mallName;
    settingForm.payConfigId = rs.payload.payConfigId;
    settingForm.payType = rs.payload.payType;
    settingForm.mallCode = rs.payload.mallCode;
    if (rs.payload.mallPageSettings) {
      Object.assign(mallPageSettings, JSON.parse(rs.payload.mallPageSettings));
    }

    // 登陆方式
    settingForm.loginType = rs.payload.loginType;

    // 外部授权登录
    settingForm.externalLoginConfigId = rs.payload.externalLoginConfigId;

    // 登录页面
    if (rs.payload.loginStyleId !== -1) {
      loginStyleIdModel.value = -2;
      settingForm.loginStyleId = rs.payload.loginStyleId;
    }

    // 短信配置
    if (rs.payload.externalSmsConfigId !== -1) {
      externalSmsConfigIdModel.value = -2;
      settingForm.externalSmsConfigId = rs.payload.externalSmsConfigId;
    }
    //通知配置
    const noticeInfo = {
      noticeType: rs.payload.noticeType,
      noticeUserIds: rs.payload.noticeUserIds,
      noticePhones: rs.payload.noticePhones,
      noticeWebhookUrls: rs.payload.noticeWebhookUrls
    }
    noticeConfigRef.value?.getFormData(noticeInfo)

  }
  loading.value = false;
};
// 设置支付平台
const setPayType = (val: any) => {
  let externalPlatformType = val.selected[0].info.externalPlatformType;
  settingForm.payType = externalPlatformType;
};

// 获取支付配置
const getConfigList = async () => {
  if (payConfigList.value.length) {
    return;
  }
  let rs: any = await sysConfigApi.getConfigList({ externalType: "pay" });
  if (rs.code == 200) {
    payConfigList.value = rs.payload;
  }
};

// 格式化折扣
const handleDiscountBlur = (e: InputEvent) => {
  let _discount = (e.target as HTMLInputElement).value;

  if (!_discount) {
    return;
  }

  if (isNaN(Number(_discount))) {
    return;
  }

  let splitDiscount = _discount.split(".");
  let intPart = Number(splitDiscount[0]);
  let digitPart = 0;

  if (splitDiscount.length > 1) {
    digitPart = Number(_discount) - intPart;
  }

  if (digitPart >= 0 && digitPart < 0.3) {
    digitPart = 0;
  } else if (digitPart >= 0.3 && digitPart < 0.7) {
    digitPart = 0.5;
  } else if (digitPart >= 0.7 && digitPart <= 1) {
    digitPart = 0;
    intPart += 1;
  }

  _discount = (intPart + digitPart).toFixed(1);

  settingForm.discount = _discount;
};

const loginStyleIdModel: Ref<number> = ref(-1);
watch(loginStyleIdModel, (newVal) => {
  if (newVal === -1) { // 系统默认
    settingForm.loginStyleId = -1
  }
})

const externalSmsConfigIdModel: Ref<number> = ref(-1);
watch(externalSmsConfigIdModel, (newVal) => {
  if (newVal === -1) { // 系统默认
    settingForm.externalSmsConfigId = -1
  }
})

const confirm = () => { };
const cancel = (type: string | number) => {
  dialogMessage.value[type] = false;
};

// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    _getOrderConfigure();
    // getConfigList();
  },
  {
    deep: true,
  }
);
onMounted(() => {
  _getOrderConfigure();
  // getConfigList();
});
</script>

<style scoped lang="scss">
:deep(.el-input) {
  width: 300px;
}

.description {
  margin-left: 20px;
}

.form-title {
  padding: 10px;
  position: relative;
}

.form-title:before {
  content: "";
  width: 5px;
  height: 16px;
  background: var(--el-color-primary);
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
}

.detail-container {
  .detail-text_line {
    white-space: nowrap;
  }
}

.nav-content {
  .tab-row {
    margin-bottom: 18px;
  }
  .tab-icons {
    display: flex;
    align-items: center;

    .img-wrapper {
      width: 50px;
      height: 50px;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 5px;
      line-height: 1.5;
      text-align: center;
      color: #999;
      cursor: pointer;
    }

    .img-wrapper:hover{
      .close {
        display: flex;
      }
    }

    .img-wrapper__selected {
      background: #f0f0f0;
    }

    .close {
      position: absolute;
      top: 0;
      right: 0;
      width: 20px;
      height: 20px;
      display: none;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
    
    .add {
      width: 50px;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: dashed 1px #999;
      margin-left:  20px;
      cursor: pointer;
    }

  }

  .tabs {
    background: #F0F0F0;
    padding: 10px;

    :deep(.el-form-item__label) {
      width: 90px !important;
    }

    .href-wrapper {
      width: 200px;
      height: 40px;
      background: #ccd2e2;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      line-height: 18px;
      font-size: 14px;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .href-wrapper__homepage {
      cursor: not-allowed;
      background: #ddd;
      color: #999;
    }
  }

  .uploader {
    display: flex;
    flex-direction: column;
    margin-right: 10px;

    .uploader-placeholder {
      margin-top: 5px;
      text-align: center;
      font-size: 12px;
      line-height: 1.3;
    }
  }
}

.fixed-button {
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
